package com.smart.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Servlet implementation class LoadServlet
 */

@Controller
public class LoadServlet {
       
	@RequestMapping(value="/upload/images/**", method = RequestMethod.GET)
    public void load(HttpServletRequest req, HttpServletResponse resp)
	{
		ServletContext sc = req.getServletContext();
		String reqURI=req.getRequestURI();
		String[] args=reqURI.split("/");
		int len=args.length;
		String resName=args[len-1];
		String realPath=sc.getAttribute("realPath").toString();
		System.out.println("realPath:"+realPath);
		//先去读取文件
		String imagePath=sc.getAttribute("imagePath").toString();
		String path=imagePath+resName;
		File f=new File(path);
		System.out.println("path:"+path);
		if(f.exists())
		{
			try {
				FileInputStream fis=new FileInputStream(f);
				byte[] data=new byte[fis.available()+1];
				fis.read(data);
				resp.setHeader("Content-type","image/jpeg");
				OutputStream out=resp.getOutputStream();
				out.write(data);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		else
		{
			System.out.println("file not exist");
		}
	}
}
